using System;
using System.IO;
using System.Net;

namespace ThatsMeSDK.Core
{
	/// <summary>
	/// Virtual Browser for Post and Get requests
	/// Works with MonoDroid
	/// </summary>
	internal class VBrowser
	{
		/// <summary>
		/// Browser Timout
		/// </summary>
		internal Int32 TimeOut { get; private set; }

		//Webrequest
		HttpWebRequest req;
		HttpWebResponse res;

		//CookieJar for Sessionhandling
		CookieContainer cookieJar;

		/// <summary>
		/// Creates a new VBrowser
		/// </summary>
		/// <param name="TimeOut">Connection Timeout</param>
		internal VBrowser(int TimeOut)
		{
			cookieJar = new CookieContainer();
			this.TimeOut = TimeOut;
		}

		/// <summary>
		/// Get Web Request
		/// </summary>
		/// <param name="uri">Content Uri</param>
		/// <returns>Returns the content of the requestet Uri</returns>
		internal string GetRequest(Uri uri)
		{
			try
			{
				req = (HttpWebRequest)HttpWebRequest.Create(uri);
				
				req.CookieContainer = cookieJar;
				req.Method = "GET";
				req.KeepAlive = true;
				req.ServicePoint.Expect100Continue = false;
				//req.Referer = uri.ToString();
				req.Timeout = TimeOut;
				req.UserAgent = ("User-Agent: TMAppSDK/1.0");
				req.ContentType = "application/x-www-form-urlencoded";
				res = (HttpWebResponse)req.GetResponse();

				return (new StreamReader(res.GetResponseStream()).ReadToEnd());
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}

		/// <summary>
		/// Post Web Request
		/// </summary>
		/// <param name="uri">Content Uri</param>
		/// <param name="PostDataBytes">Post data for the request</param>
		/// <returns>Returns the content of the requestet Uri</returns>
		internal string PostRequest(Uri uri, byte[] PostDataBytes)
		{
			try
			{
				req = (HttpWebRequest)HttpWebRequest.Create(uri);

				req.CookieContainer = cookieJar;
				req.Method = "POST";
				req.KeepAlive = false;
				req.Referer = uri.ToString();
				req.ServicePoint.Expect100Continue = false;
				req.Timeout = (TimeOut);
				req.UserAgent = ("User-Agent: TMAppSDK/1.0");
				req.ContentType = "application/x-www-form-urlencoded";

				req.ContentLength = PostDataBytes.Length;
				Stream stream = req.GetRequestStream();
				stream.Write(PostDataBytes, 0, PostDataBytes.Length);
				stream.Close();

				res = (HttpWebResponse)req.GetResponse();

				return (new StreamReader(res.GetResponseStream()).ReadToEnd());
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}
	}
}
